package com.huayushu.controller;

import com.huayushu.enums.VideoStatusEnum;
import com.huayushu.pojo.Bgm;
import com.huayushu.pojo.Comments;
import com.huayushu.pojo.Videos;
import com.huayushu.service.BgmService;
import com.huayushu.service.VideoService;
import com.huayushu.utils.FetchVideoCover;
import com.huayushu.utils.JSONResult;
import com.huayushu.utils.MergeVideoMp3;
import com.huayushu.utils.PagedResult;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author: huayushu luming
 * @date: 2019-11-28 19:07
 * @desc:
 **/
@RestController
@Api(value = "视频相关业务的接口", tags = {"视频相关业务的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController {
    @Autowired
    private BgmService bgmService;
    @Autowired
    private VideoService videoService;

    @ApiOperation(value = "上传视频", notes = "上传视频接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "bgmId", value = "背景音乐id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoSeconds", value = "背景音乐播放长度", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoWidth", value = "视频宽度", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoHeight", value = "视频高度", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "desc", value = "视频描述", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public JSONResult uplaodFace(String userId, String bgmId, double videoSeconds,
                                 int videoWidth, int videoHeight, String desc,
                                 @ApiParam(value = "短视频", required = true) MultipartFile file) throws Exception {
        //入参判断
        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("用户id不能为空...");
        }
        //文件保存的命名空间
        //String fileSpace = "E:/huayushu_video_dev";
        //保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/video";
        //保存视频截图保存
        String coverPathDB = "/" + userId + "/video";

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        String finalVideoPath = "";
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                //获取视频名称
                String fileNamePrefix = fileName.split("\\.")[0];

                if (StringUtils.isNotBlank(fileName)) {
                    //文件上传的最终保存路径
                    finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
                    //设置数据库保存的路径
                    uploadPathDB += ("/" + fileName);
                    coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg";

                    File outFile = new File(finalVideoPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return JSONResult.errorMsg("上传出错了！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("上传出错了！");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }

        //判断bgmId是否为空，如果不为空
        //那就查询bgm的信息，并且合并视频，生产新的视频
        if (StringUtils.isNotBlank(bgmId)) {
            Bgm bgm = bgmService.queryBgmById(bgmId);
            String bgmPath = FILE_SPACE + bgm.getPath();
            MergeVideoMp3 mergeVideoMp3 = new MergeVideoMp3(FFMPEG_EXE);
            String videoInputPath = finalVideoPath;
            String videoOutputName = UUID.randomUUID().toString() + ".mp4";
            uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName;
            finalVideoPath = FILE_SPACE + uploadPathDB;
            mergeVideoMp3.convertor(videoInputPath, bgmPath, videoSeconds, finalVideoPath);
        }
        System.out.println("数据库地址：" + uploadPathDB);
        System.out.println("最终生成地址：" + finalVideoPath);

        //进行视频截图
        FetchVideoCover ffmpeg = new FetchVideoCover(FFMPEG_EXE);
        ffmpeg.getCover(finalVideoPath, FILE_SPACE + coverPathDB);
        System.out.println("视频封面地址：" + FILE_SPACE + coverPathDB);

        //保存视频信息到数据库
        Videos videos = new Videos();
        videos.setAudioId(bgmId);
        videos.setUserId(userId);
        videos.setVideoSeconds((float) videoSeconds);
        videos.setVideoHeight(videoHeight);
        videos.setVideoWidth(videoWidth);
        videos.setVideoDesc(desc);
        videos.setVideoPath(uploadPathDB);
        videos.setCoverPath(coverPathDB);
        videos.setStatus(VideoStatusEnum.SUCCESS.value);
        videos.setCreateTime(new Date());
        String videoId = videoService.saveVideo(videos);
        return JSONResult.ok(videoId);
    }


    @ApiOperation(value = "上传封面", notes = "上传封面接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId", value = "视频主键id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"),
    })
    @PostMapping(value = "/uploadCover", headers = "content-type=multipart/form-data")
    public JSONResult uploadCover(String videoId, String userId,
                                  @ApiParam(value = "视频封面", required = true) MultipartFile file) throws Exception {
        //入参判断
        if (StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("视频主键id和用户id不能为空...");
        }
        //文件保存的命名空间
        //String fileSpace = "E:/huayushu_video_dev";
        //保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/video";

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        String finalCoverPath = "";
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (StringUtils.isNotBlank(fileName)) {
                    //文件上传的最终保存路径
                    finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
                    //设置数据库保存的路径
                    uploadPathDB += ("/" + fileName);

                    File outFile = new File(finalCoverPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return JSONResult.errorMsg("上传出错了！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("上传出错了！");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        videoService.updateVideo(videoId, uploadPathDB);
        return JSONResult.ok();
    }

    /**
     * 分页和搜索查询视频列表
     *
     * @param videos
     * @param isSaveRecord: 1-需要保存
     *                      0-不需要保存
     * @param page
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/showAll")
    public JSONResult showAll(@RequestBody Videos videos, Integer isSaveRecord, Integer page,Integer pageSize) throws Exception {
        if (page == null) {
            page = 1;
        }
        if(pageSize==null){
            pageSize=PAGE_SIZE;
        }
        PagedResult pagedResult = videoService.getAllVideos(videos, isSaveRecord, page, pageSize);
        return JSONResult.ok(pagedResult);
    }

    /**
     * @Description: 我收藏(点赞)过的视频列表
     */
    @PostMapping("/showMyLike")
    public JSONResult showMyLike(String userId, Integer page, Integer pageSize) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return JSONResult.ok();
        }

        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 6;
        }

        PagedResult videosList = videoService.queryMyLikeVideos(userId, page, pageSize);

        return JSONResult.ok(videosList);
    }

    /**
     * @Description: 我关注的人发的视频
     */
    @PostMapping("/showMyFollow")
    public JSONResult showMyFollow(String userId, Integer page) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return JSONResult.ok();
        }

        if (page == null) {
            page = 1;
        }

        int pageSize = 6;

        PagedResult videosList = videoService.queryMyFollowVideos(userId, page, pageSize);

        return JSONResult.ok(videosList);
    }

    /**
     * 热搜词排序查询
     *
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/hot")
    public JSONResult hot() throws Exception {

        return JSONResult.ok(videoService.getHotwords());
    }

    /**
     * 用户点赞
     *
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/userLike")
    public JSONResult userLike(String userId, String videoId, String videoCreaterId) throws Exception {
        videoService.userLikeVideo(userId, videoId, videoCreaterId);
        return JSONResult.ok();
    }

    /**
     * 用户取消点赞
     *
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/userUnLike")
    public JSONResult userUnLike(String userId, String videoId, String videoCreaterId) throws Exception {
        videoService.userUnLikeVideo(userId, videoId, videoCreaterId);
        return JSONResult.ok();
    }

    @PostMapping("/saveComment")
    public JSONResult saveComment(@RequestBody Comments comments,String fatherCommentId,String toUserId)throws Exception{
        comments.setFatherCommentId(fatherCommentId);
        comments.setToUserId(toUserId);
        videoService.saveComment(comments);
        return JSONResult.ok();
    }

    @PostMapping("/getVideoComments")
    public JSONResult getVideoComments(String videoId,Integer page,Integer pageSize)throws Exception{
        if(StringUtils.isBlank(videoId)){
            return JSONResult.ok();
        }
        //分页查询视频列表
        if(page==null){
            page=1;
        }
        if(pageSize==null){
            pageSize=10;
        }
        PagedResult list=videoService.getAllComments(videoId,page,pageSize);
        return  JSONResult.ok(list);
    }
}
